<template>
  <div class="app-Inquiry" style="margin: 0 !important;">
    <div class="top-container">
      <el-form
        :inline="true"
        :model="formInline"
        ref="formInline"
        class="demo-form-inline"
        style="display: block !important;"
      >
        <el-form-item label="后台单号" style="margin-bottom: 15px!important;">
          <el-input
            v-model.trim="formInline.xmbzNo"
            clearable
            size="medium"
            placeholder="后台单号"
            style="width: 163px;"
          ></el-input>
        </el-form-item>
        <el-form-item label="平台单号" style="margin-bottom: 15px!important;">
          <el-input
            v-model.trim="formInline.platformOrderId"
            clearable
            size="medium"
            placeholder="平台单号"
          ></el-input>
        </el-form-item>
        <el-form-item label="城市" style="margin-bottom: 15px!important;">
          <el-select
            ref="deptRef"
            v-model="deptName"
            placeholder="城市"
            size="medium"
            style="width: 100px;"
            @change="handleCity"
            @keydown.native="selectBlur($event)"
          >
            <el-option
              v-for="(house,citykey) in cityselect"
              :key="citykey"
              :label="house.deptName"
              :value="{value:house.id,label:house.deptName}"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" style="margin-bottom: 15px!important;">
          <el-input
            v-model.trim="formInline.receiverPhone"
            clearable
            size="medium"
            placeholder="手机号"
            style="width: 135px"
          ></el-input>
        </el-form-item>
        <el-form-item label="操作人" prop="confirmOperator" style="margin-bottom: 15px!important;">
          <el-input
            v-model.trim="formInline.confirmOperator"
            clearable
            size="medium"
            placeholder="操作人"
            style="width: 125px"
          ></el-input>
        </el-form-item>
        <el-form-item label="配送员" prop="delivery" style="margin-bottom: 15px!important;">
          <el-input
            v-model.trim="formInline.delivery"
            clearable
            size="medium"
            placeholder="配送员"
            style="width: 125px"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态" style="margin-right: 0;margin-bottom: 15px!important;">
          <el-select
            ref="statusRef"
            v-model="formInline.status"
            clearable
            size="medium"
            placeholder="状态"
            style="width: 130px"
            @keydown.native="selectBlur($event)"
          >
            <el-option
              v-for="item in statusList"
              :key="item.status"
              :label="item.statusName"
              :value="item.status"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="渠道类别" style="margin-bottom: 15px!important;margin-left: 10px;">
          <el-select
            ref="channelTypeRef"
            v-model="formInline.channelType"
            @keydown.native="keydown($event)"
            clearable
            filterable
            size="medium"
            placeholder="渠道类别"
            style="width: 155px"
          >
            <el-option
              v-for="(channelitem,channel) in channelTypellist"
              :key="channel"
              :label="channelitem.channelName"
              :value="channelitem.channelKey"
            >
              <span
                :data-id="channelitem.id"
                style="display: inline-block;width: 150px;padding: 0 20px;margin-left: -20px;"
                @click="getchannelTypeId($event)"
              >{{ channelitem.channelName }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="渠道" style="margin-bottom: 15px!important;">
          <el-select
            ref="channelRef"
            v-model="formInline.channel"
            @keydown.native="keydown($event)"
            clearable
            filterable
            size="medium"
            placeholder="渠道"
            style="width: 155px"
          >
            <el-option
              v-for="(channelitem,channel) in channerllist"
              :key="channel"
              :label="channelitem.channelName"
              :value="channelitem.channelKey"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分仓" style="margin-bottom: 15px!important;">
          <el-select
            ref="barnchWarehouseRef"
            v-model="formInline.warehouseId"
            @keydown.native="selectBlur($event)"
            clearable
            filterable
            size="medium"
            placeholder="分仓"
            style="width: 155px"
          >
            <el-option
              v-for="(item,index) in barnchWarehouselist"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item sytle="dispaly:flex">
          <el-select
            ref="selectRef"
            v-model="formInline.select"
            placeholder="时间"
            size="medium"
            @keydown.native="selectBlur($event)"
            style="width: 110px;margin: 0 8px;"
          >
            <el-option label="配送时间" value="配送时间"></el-option>
            <el-option label="下单时间" value="下单时间"></el-option>
          </el-select>
          <el-date-picker
            v-model="timeValue"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :picker-options="pickerOptions"
            :default-time="['00:00:00', '23:59:59']"
            value-format="yyyy-MM-dd HH:mm"
            format="yyyy-MM-dd HH:mm"
            size="medium"
            align="right"
          ></el-date-picker>
          <!-- <el-date-picker v-model="formInline.StartTime" type="datetime" placeholder="选择配送时间" align="right"
            :picker-options="pickerOptions" value-format="yyyy-MM-dd HH:mm:ss" size="medium" style="width: 220px;"></el-date-picker>
          <span class="line" :span="1" align="center">--</span>
          <el-date-picker v-model="formInline.EndTime" type="datetime" placeholder="选择配送时间" align="right"
          :picker-options="pickerOptions" value-format="yyyy-MM-dd HH:mm:ss" size="medium" style="width: 220px;"></el-date-picker>-->
        </el-form-item>
        <el-form-item style="margin-bottom: 15px!important;">
          <el-button
            type="primary"
            @click="onSubmit('formInline')"
            size="medium"
            plain
            icon="el-icon-search"
            style="margin-left: 30px;"
          >查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-container">
      <el-table
        class="table-width"
        :data="querylist"
        header-row-class-name="table-top"
        :row-class-name="tableRowClassName"
        @sort-change="changeTableSort"
        style="width: 100%"
      >
        <el-table-column prop="xmbzNo" label="后台单号" align="center" min-width="60">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.xmbzNo }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="配送时间"
          :sortable="'deliveryTimeSort'"
          align="center"
          prop="deliveryStartTime"
          min-width="85"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.deliveryStartTime == ''" style="margin-left: 10px">立即配送</span>
            <span
              v-if="scope.row.deliveryStartTime !== ''"
              style="display: flex;flex-direction: column;"
            >
              <span>{{ scope.row.deliveryStartTime.slice(0,10) }}</span>
              <span>{{ scope.row.deliveryStartTime.slice(11,16) }}~{{ scope.row.deliveryEndTime.slice(11,16) }}</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="下单时间"
          :sortable="'orderTimeSort'"
          align="center"
          prop="orderTime"
          min-width="77"
        >
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.orderTime.slice(5,16) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="收货人" prop="receiverName" align="center" min-width="50">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.receiverName }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="平台单号" prop="platformOrderId" align="center">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.platformOrderId }}</span>
          </template>
        </el-table-column>-->
        <el-table-column label="手机号" prop="receiverPhone" align="center" min-width="60">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.receiverPhone }}</span>
          </template>
        </el-table-column>
        <el-table-column label="配送地址" prop="receiverAddress" align="center" min-width="150px">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.receiverAddress }}</span>
          </template>
        </el-table-column>
        <el-table-column label="渠道" prop="channelName" align="center" min-width="53px">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.channelName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="订单状态" prop="statusName" align="center" min-width="55">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.statusName }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column
          label="商品名称"
          prop=""
          align="center"
          width="180"
          :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.channelName }}</span>
          </template>
        </el-table-column>-->
        <el-table-column label="异常反馈" prop="abnormalContent" align="center" min-width="55">
          <template slot-scope="scope">
            <span style="margin-left: 10px;color: red;">{{ scope.row.abnormalContent }}</span>
          </template>
        </el-table-column>
        <el-table-column label="客服备注" prop="customerServiceNotes" align="center" min-width="55">
          <template slot-scope="scope">
            <span style="margin-left: 10px;color: red;">{{ scope.row.customerServiceNotes }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作人" prop="confirmOperator" align="center" min-width="43">
          <template slot-scope="scope">
            <span style="margin-left: 10px;color: red;">{{ scope.row.confirmOperator }}</span>
          </template>
        </el-table-column>
        <el-table-column label="配送员" prop="delivery" align="center" min-width="45">
          <template slot-scope="scope">
            <span style="margin-left: 10px;color: red;">{{ scope.row.delivery }}</span>
          </template>
        </el-table-column>
        <el-table-column label="分仓" prop="branchWarehouse" align="center" min-width="35">
          <template slot-scope="scope">
            <span style="margin-left: 10px;color: red;">{{ scope.row.branchWarehouse }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="说明" align="center" min-width="105px">
          <template slot-scope="scope">
            <div
              class="el-col-primary dangerbutton"
              v-if="scope.row.replaceCake == 1 ? true : false"
            >蛋糕原料缺失</div>
            <!-- <div class="el-col-primary mainbutton" v-if="scope.row.replaceDeliveryTime  == 1 ? true : false" style="margin-top: 5px;">运力紧张</div> -->

            <div
              class="el-col-primary infobutton"
              v-if="scope.row.refundNotReturnName === '退款不退货' ? true : false"
            >退款不退货</div>
            <div class="el-col-primary warnbutton" v-if="scope.row.refundMark == '平台退款中'">平台退款中</div>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="left" min-width="55">
          <template slot-scope="scope">
            <!-- <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button> -->
            <i
              class="el-icon-edit"
              @mouseenter="aditenterColor(scope.$index, scope.row)"
              @mouseleave="aditleaveColor(scope.$index, scope.row)"
              :class="scope.$index == aditFlag ? 'active':'buttoncolor'"
              @click="handleEdit(scope.$index, scope.row)"
              style="cursor: pointer!important;"
            >编辑</i>
            <br>
            <i
              class="el-icon-mobile"
              @mouseenter="dateenterColor(scope.$index, scope.row)"
              @mouseleave="dateleaveColor(scope.$index, scope.row)"
              :class="scope.$index == dateFlag ? 'active':'buttoncolor'"
              style="cursor: pointer!important;"
              @click="handleOrderLog(scope.row)"
            >日志</i>
            <br>
            <i
              class="el-icon-view"
              @mouseenter="viewenterColor(scope.$index, scope.row)"
              @mouseleave="viewleaveColor(scope.$index, scope.row)"
              :class="scope.$index == viewFlag ? 'active':'buttoncolor'"
              style="cursor: pointer!important;"
              @click="handleViewLog(scope.$index, scope.row)"
            >查看</i>
            <br>
            <i
              @mouseenter="SMSenterColor(scope.$index, scope.row)"
              @mouseleave="SMSleaveColor(scope.$index, scope.row)"
              :class="scope.$index == SMSFlag ? 'active':'buttoncolor'"
              style="cursor: pointer!important;font-style: normal"
              @click="handleSMS(scope.$index, scope.row)"
            >短信记录</i>
            <br>
            <i
              @mouseenter="SMSsendenterColor(scope.$index, scope.row)"
              @mouseleave="SMSsendleaveColor(scope.$index, scope.row)"
              :class="scope.$index == SMSsendFlag ? 'active':'buttoncolor'"
              style="cursor: pointer!important;font-style: normal"
              @click="handleSMSsend(scope.$index, scope.row)"
            >短信发送</i>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="formInline.page"
        :limit.sync="formInline.size"
        @pagination="getList"
      />
    </div>
    <el-dialog title="日志" :visible.sync="LogFormVisible" width="400">
      <div class="radio">显示方式：
        <el-radio-group v-model="reverse">
          <el-radio :label="true">倒序</el-radio>
          <el-radio :label="false">正序</el-radio>
        </el-radio-group>
      </div>
      <el-timeline :reverse="reverse">
        <el-timeline-item
          v-for="(activity, index) in getOrderOperateLogList"
          :key="index"
          :icon="activity.icon"
          :type="activity.type"
          :color="activity.color"
          :size="activity.size"
          :timestamp="activity.createTime"
        >
          <h5>{{activity.operator}}</h5>
          <h4 v-html="activity.action">{{activity.action}}</h4>
        </el-timeline-item>
      </el-timeline>
    </el-dialog>
    <el-dialog title="发送短信" :visible.sync="SMSsendviewFlag" :before-close="handleSMSClose" width="45%">
      <el-form :model="SMSruleForm" status-icon :rules="SMSrules" ref="SMSruleForm" label-width="100px" class="demo-ruleForm" style="width: 90%;">
        <el-form-item label="发送给" prop="phoneNumbers">
          <el-input v-model.number="SMSruleForm.phoneNumbers" placeholder="请输入手机号码" clearable maxlength="11" @keydown.native="temNselectBlur($event)"></el-input>
        </el-form-item>
        <el-form-item label="模板类型" prop="templateNames">
          <el-select id="InauirytempName" v-model="SMSruleForm.templateNames" filterable placeholder="请选择短信模板" @change="getSmsTemplatePageInfo()" clearable @keydown.native="temNselectBlur($event)" style="width: 100%;">
            <el-option
              v-for="item in templateList"
              :key="item.id"
              :label="item.templateName"
              :value="item.templateContent"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="短信内容" prop="content">
          <el-input :required="false" type="textarea" v-model="SMSruleForm.content" placeholder="短信内容" :readonly="true" :autosize="SMSruleForm.content == '' ? { minRows: 2, maxRows: 4} : ''"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="SMSresetForm('SMSruleForm')">取消</el-button>
          <el-button type="primary" @click="SMSsubmitForm('SMSruleForm')">确认</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  orderList, // 查询
  statusList, // 订单状态
  forceUnlock, // 强制解锁
  startUpdate, //开始修改
  getWarehouseListByCityId,
  getOrderOperateLog, // 订单日志
  add0rderOperateLog // 添加订单操作日志
} from "@/api/pending";
import {
  SmsTemplateNameAndContent,// 短信模板
  sendInquirySms,// 短信发送
  getDefaultSmsTemplate,// 返回订单要发的短信内容
} from "@/api/customer";
import {
  citySelect, // 城市
  getOrderChannelList, // 渠道
  getOrderChannelTypeList // 渠道类别列表
} from "@/api/createOrder";
import Pagination from "@/components/Pagination"; // 分页
export default {
  components: {
    Pagination
  },
  data() {
    var checkPhone = (rule, value, callback) => {
      setTimeout(() => {
        if (value !== "") {
          if (!Number.isInteger(value)) {
            callback(new Error("请输入数字值"));
          } else {
            if (value.toString().length !== 11) {
              callback(new Error("号码长度应为11位"));
            } else {
              callback();
            }
          }
        }
      }, 1000);
    };
    return {
      barnchWarehouselist: [],
      total: 0,
      deptId: "",
      deptName: "",
      formInline: {
        deptId: 0, // 城市id
        xmbzNo: "", // 后台单号
        platformOrderId: "", // 平台单号
        status: "",
        channelType: '',// 渠道类别
        channel: "", // 渠道
        select: "配送时间",
        StartTime: "",
        EndTime: "",
        receiverPhone: "", // 手机号
        deliveryStartTime: "", // 配送开始时间
        deliveryEndTime: "", // 配送结束时间
        orderTimeStart: "", // 下单开始时间
        orderTimeEnd: "", // 下单结束时间
        orderTimeSort: 0, // 下单时间排序
        deliveryTimeSort: 0, // 配送时间排序
        delivery: "", //配送员
        confirmOperator: "", //操作人
        warehouseId:'',

        page: 1,
        limit: 10,
        size: 10
      },
      channerllist: "", //渠道
      querylist: [],
      Loading: true,
      statusList: "", // 状态
      pickerOptions: {
        onPick: obj => {
          this.pickerMinDate = new Date(obj.minDate).getTime();
        },
        disabledDate: time => {
          if (this.pickerMinDate) {
            const day1 = 31 * 24 * 3600 * 1000;
            let maxTime = this.pickerMinDate + day1;
            let minTime = this.pickerMinDate - day1;
            return time.getTime() > maxTime || time.getTime() < minTime;
          }
        }
      },
      // pickerOptions: {
      //   shortcuts: [{
      //     text: '最近一周',
      //     onClick(picker) {
      //       const end = new Date();
      //       const start = new Date();
      //       start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      //       picker.$emit('pick', [start, end]);
      //     }
      //   }, {
      //     text: '最近一个月',
      //     onClick(picker) {
      //       const end = new Date();
      //       const start = new Date();
      //       start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      //       picker.$emit('pick', [start, end]);
      //     }
      //   }, {
      //     text: '最近三个月',
      //     onClick(picker) {
      //       const end = new Date();
      //       const start = new Date();
      //       start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      //       picker.$emit('pick', [start, end]);
      //     }
      //   }]
      // },
      cityselect: "", // 城市获取列表
      channelTypellist: "", // 渠道类别列表
      getChannelList: {
        // 渠道列表
        parentId: ""
      },
      startUpdateList: {
        //开始修改列表
        orderId: 1
      },
      getOrderOperateLogList: [],
      LogFormVisible: false,
      reverse: false,
      aditFlag: null,
      dateFlag: null,
      viewFlag: null, // 查看按钮划进划出
      SMSFlag: null, // 短信记录划进划出
      SMSsendFlag: null,// 短信发送划进划出
      authsList: ["在线组", "PHONE", "ORDER"],
      timeValue: [], // 查询时间值
      timeValueFlag: false, // 查询时间是否大于31天标记
      SMSruleForm: {// 短信发送
        phoneNumbers: '',
        templateName: '',// 短信模板
        templateNames: '',
        content: ''
      },
      SMSrules: {
        phoneNumbers: [
          { required: true, validator: checkPhone,trigger: 'change' },
        ],
        templateNames: [{ required: true, message: '请选择短信模板', trigger: 'change' }],
      },
      SMSsendviewFlag: false,// 短信发送弹框
      templateList: [],//短信模板
    };
  },
  created() {
    window.addEventListener("keydown", this.keyupEnter);
  },
  watch: {
    // "formInline.select"() {
    //   this.queryTime();
    // }
    'SMSruleForm.templateNames'() {
      setTimeout(() => {
        if(document.getElementById('InauirytempName').value == '小熊猫电话') this.getdefaulttem();
      },500)
    }
  },
  mounted() {
    citySelect(this.cityLi).then(res => {
      this.roleName = JSON.parse(window.localStorage.getItem('saber-userInfo')).content.authority;
      // console.log('roleName',this.roleName);
      if(this.roleName.indexOf('administrator') > -1 || this.roleName.indexOf('CSD') > -1 ||
        this.roleName.indexOf('admin') > -1 || this.roleName.indexOf('PHONE') > -1 ||
        this.roleName.indexOf('ORDER') > -1 || this.roleName.indexOf('AFTER') > -1 ||
        this.roleName.indexOf('生产总监') > -1 || this.roleName.indexOf('运力部门') > -1 ||
        this.roleName.indexOf('运力总监') > -1 || this.roleName.indexOf('调度部经理') > -1 ||
        this.roleName.indexOf('调度') > -1 || this.roleName.indexOf('商品部门') > -1 ||
        this.roleName.indexOf('营销部运营') > -1 || this.roleName.indexOf('营销部经理') > -1 ||
        this.roleName.indexOf('客服经理') > -1 || this.roleName.indexOf('客服权限管理') > -1 ||
        this.roleName.indexOf('客服主管') > -1 || this.roleName.indexOf('在线组') > -1 ||
        this.roleName.indexOf('运营中心') > -1 || this.roleName.indexOf('品牌事业部') > -1 ||
        this.roleName.indexOf('设计组') > -1 || this.roleName.indexOf('内容事业部') > -1 ||
        this.roleName.indexOf('内容组') > -1 || this.roleName.indexOf('三方事业部') > -1 ||
        this.roleName.indexOf('运营主管') > -1 || this.roleName.indexOf('美团团购') > -1 ||
        this.roleName.indexOf('阿里系平台') > -1 || this.roleName.indexOf('用户运营事业部') > -1 || this.roleName.indexOf('用户运营组') > -1 ||
        this.roleName.indexOf('微商城事业部') > -1 || this.roleName.indexOf('高级运营经理') > -1 ||
        this.roleName.indexOf('美团外卖') > -1 || this.roleName.indexOf('商品经理') > -1 ||
        this.roleName.indexOf('视频剪辑') > -1 || this.roleName.indexOf('营销总监') > -1 ||
        this.roleName.indexOf('营销部门权限管理') > -1 || this.roleName.indexOf('运力权限管理') > -1 ||
        this.roleName.indexOf('微商城组长') > -1 || this.roleName.indexOf('总部客服') > -1 || this.roleName.indexOf('客服数据员') > -1 ||
        this.roleName.indexOf('客服组长') > -1 || this.roleName.indexOf('财务') > -1 ||
        this.roleName.indexOf('好评返现审批') > -1 || this.roleName.indexOf('成本会计') > -1 ||
        this.roleName.indexOf('后勤中心') > -1 || this.roleName.indexOf('微商城组员') > -1 ||
        this.roleName.indexOf('人事') > -1 || this.roleName.indexOf('运营助理/天猫客服') > -1
      ) res.data.data.unshift({
              id: 0,
              deptName: "全国"
            });
      this.deptName = res.data.data[0].deptName;
      this.formInline.deptId = res.data.data[0].id;
      this.cityselect = res.data.data;
    });
    this.getWarehouseList();
    // this.deptName=JSON.parse(window.localStorage.getItem("saber-areaname")).content;
    // this.formInline.deptId=JSON.parse(window.localStorage.getItem("saber-areaId")).content;
    // 渠道类别列表
    getOrderChannelTypeList().then(res => {
      this.channelTypellist = res.data.data;
    });
    // 状态列表接口
    statusList().then(res => {
      this.statusList = res.data.data;
      // console.log(res.data.data)
    });
    this.getDeliveryTime();
    this.getList();
    // 城市

    // this.getCurrentTime()
  },
  methods: {
    // 获取今天的时间
    getCurrentTime() {
      let nowYear = new Date().getFullYear();
      let nowMonth =
        new Date().getMonth() + 1 < 10
          ? "0" + (new Date().getMonth() + 1)
          : new Date().getMonth() + 1;
      let nowDate =
        new Date().getDate() < 10
          ? "0" + new Date().getDate()
          : new Date().getDate();
      // let currentTime = new Date();
      // let year = currentTime.getFullYear();
      // let month = currentTime.getMonth() + 1 < 10 ? '0' + (currentTime.getMonth() + 1) : currentTime.getMonth() + 1;
      // let day = currentTime.getDate() < 10 ? '0' + currentTime.getDate() : currentTime.getDate();
      this.formInline.StartTime =
        nowYear + "-" + nowMonth + "-" + nowDate + " 00:00:00";
      this.formInline.EndTime =
        nowYear + "-" + nowMonth + "-" + nowDate + " 23:59:59";
      this.formInline.deliveryStartTime = this.formInline.StartTime;
      this.formInline.deliveryEndTime = this.formInline.EndTime;
      this.formInline.orderTimeStart = "";
      this.formInline.orderTimeEnd = "";
      this.getList();
      // console.log('this.formInline.deliveryStartTime',this.formInline.deliveryStartTime)
    },
    // 获取城市
    handleCity(data) {
      // console.log(data,'data')
      if (data) {
        this.deptName = data.label;
        this.formInline.deptId = data.value;
      } else {
        this.formInline.deptId = JSON.parse(
          window.localStorage.getItem("saber-areaId")
        ).content;
        this.deptName = JSON.parse(
          window.localStorage.getItem("saber-areaname")
        ).content;
      }
       this.getWarehouseList();
    },
    getWarehouseList() {
      getWarehouseListByCityId({ cityId: this.formInline.deptId }).then(res => {
        this.barnchWarehouselist = res.data.data;
        // console.log(res, "res");
        // console.log("工单日志", res.data.data);
      });
    },

    handleOrderLog(item) {
      this.reverse = false;
      this.LogFormVisible = true;
      getOrderOperateLog({ orderId: item.id }).then(res => {
        // 订单日志
        console.log("工单日志", res.data.data);
        this.getOrderOperateLogList = res.data.data;
      });
    },
    onSubmit() {
      this.formInline.page = 1;
      if (this.formInline.select === "配送时间") {
        this.formInline.distinguishingFields = "1";
      } else {
        this.formInline.distinguishingFields = "2";
      }
      this.getList();
    },
    // 点击编辑，打开详情
    handleEdit(index, row) {
      var authority = JSON.parse(window.localStorage.getItem("saber-userInfo"))
        .content.authority;

      const { href } = this.$router.resolve({
        path: `/orderdetail`,
        query: {
          id: row.id,
          cityId: row.deptId,
          deptName: row.deptName,
          kind: "Inquiry-order"
        }
      });
      this.startUpdateList.orderId = row.xmbzNo;
      let orderId = row.id;
      startUpdate(this.startUpdateList)
        .then(res => {
          if (res.data.success == true) {
            let type = 98;
            this.add0rderInquiry(orderId, type); // 解锁日志
            window.open(href, "_blank");
          } else if (res.data.success == false) {
            var authorityArr = authority.split(",");

            if (authorityArr.length > 1) {
              //多角色
              const auths = this.dealData(authorityArr);
              this.authsList.forEach(p => {
                auths.map(c => {
                  if (p === c.value) {
                    c.checked = false;
                  }
                });
              });
              const endData = auths.filter(item => item.checked);
              if (endData.length >= 1) {
                this.$confirm("是否需要强制解锁此订单?", "提示", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning"
                })
                  .then(() => {
                    forceUnlock(this.startUpdateList).then(res => {
                      if (res.data.code == 200) {
                        type = 100;
                        this.add0rderInquiry(orderId, type); // 解锁日志
                        this.$message({
                          type: "success",
                          message: "解锁成功!"
                        });
                        window.open(href, "_blank");
                      }
                    });
                  })
                  .catch(() => {
                    this.$message({
                      type: "info",
                      message: "已取消解锁成功"
                    });
                  });
              } else {
                this.$message({
                  type: "warning",
                  message: "订单已被锁定"
                });
              }
            } else {
              //单角色
              if (
                authority == "ORDER" ||
                authority == "在线组" ||
                authority == "PHONE"
              ) {
                this.$message({
                  type: "warning",
                  message: "订单已被锁定"
                });
              } else {
                this.$confirm("是否需要强制解锁此订单?", "提示", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning"
                })
                  .then(() => {
                    forceUnlock(this.startUpdateList).then(res => {
                      if (res.data.code == 200) {
                        type = 100;
                        this.add0rderInquiry(orderId, type); // 解锁日志
                        this.$message({
                          type: "success",
                          message: "解锁成功!"
                        });
                        window.open(href, "_blank");
                      }
                    });
                  })
                  .catch(() => {
                    this.$message({
                      type: "info",
                      message: "已取消解锁成功"
                    });
                  });
              }
            }
          }
        })
        .catch(error => {
          console.log("333", error);
        });
    },
    dealData(authority) {
      const newArr = [];
      authority.forEach(item => {
        newArr.push({
          checked: true,
          value: item
        });
      });
      return newArr;
    },
    // 查询列表
    getList() {
      this.queryTime();
      if(this.formInline.xmbzNo !== '' || this.formInline.platformOrderId !== '' || this.formInline.receiverPhone !== '') {
        this.formInline.deliveryStartTime = "";
        this.formInline.deliveryEndTime = "";
        this.formInline.orderTimeStart = "";
        this.formInline.orderTimeEnd = "";
      } else {
        if(this.formInline.confirmOperator !== '' ||
          this.formInline.delivery !== '' || this.formInline.status !== '' ||
          this.formInline.channelType !== '' || this.formInline.channel !== '' ||
          this.formInline.warehouseId !== ''
        ) {
          if(this.formInline.deliveryStartTime == "" && this.formInline.deliveryEndTime == "" && this.formInline.orderTimeStart == "" && this.formInline.orderTimeEnd == "") {
            this.$message.warning('请输入搜索时间，且跨度不能超过31天');
            return false;
          }
        }
      }
      if (!this.timeValueFlag) {
        this.Loading = true;
        if (this.formInline.select === "配送时间") {
          this.formInline.distinguishingFields = "1";
        } else {
          this.formInline.distinguishingFields = "2";
        }
        orderList(this.formInline).then(res => {
          this.total = res.data.data.total;
          this.querylist = res.data.data.rows;
          // this.querylist.forEach(item => {
          //   item.customerServiceNotes = unescape(item.customerServiceNotes)
          // })
          // console.log('res',res.data.data)
          // this.querylist.forEach((item, index) => {
          //   this.querylist[index].getHour = this.getHour(this.querylist[index].deliveryEndTime).toFixed(2)
          //   // console.log(this.querylist[index].getHour,'this.querylist[index].getHour')
          //   if (this.querylist[index].getHour > 3) {
          //     // console.log(this.querylist[index].getHour, '>3')
          //     this.querylist[index].getHour = true
          //   } else if (this.querylist[index].getHour < 3) {
          //     // console.log(this.querylist[index].getHour,'<3') // data00000
          //     this.querylist[index].getHour = false
          //   } else if (this.querylist[index].getHour.toString() === 'NaN') {
          //     // console.log('/3')
          //     this.querylist[index].getHour = true
          //   }
          // })
          setTimeout(() => {
            this.Loading = false;
          }, 0.5 * 1000);
        });
      }
    },
    // 紧急单颜色变化
    tableRowClassName({ row }) {
      // console.log(row.getHour,row.id,'row')
      if (row.getHour === false) {
        // console.log('false')
        return "warning-row";
      }
      return "";
    },
    // 计算时间差
    getHour(endTime) {
      let nowYear = new Date().getFullYear();
      let nowMonth =
        new Date().getMonth() + 1 < 10
          ? "0" + (new Date().getMonth() + 1)
          : new Date().getMonth() + 1;
      let nowDate =
        new Date().getDate() < 10
          ? "0" + new Date().getDate()
          : new Date().getDate();
      let nowHours =
        new Date().getHours() < 10
          ? "0" + new Date().getHours()
          : new Date().getHours();
      let nowMinutes =
        new Date().getMinutes() < 10
          ? "0" + new Date().getMinutes()
          : new Date().getMinutes();
      // console.log(e.currentTarget.dataset.time,nowYear + '-' + nowMonth + '-' + nowDate + ' ' + nowHours + ':' + nowMinutes)
      let nowTime =
        nowYear +
        "-" +
        nowMonth +
        "-" +
        nowDate +
        " " +
        nowHours +
        ":" +
        nowMinutes;
      let s1 = new Date(endTime.replace(/-/g, "/"));
      // console.log('s1',s1)
      let s2 = new Date(nowTime.replace(/-/g, "/"));
      let ms = Math.abs(s1.getTime() - s2.getTime());
      let getHour = ms / 1000 / 60 / 60;
      // console.log('getHour',getHour)
      return getHour;
    },
    // 选择渠道类型
    getchannelTypeId(e) {
      // 渠道列表接口
      this.getChannelList.parentId = e.currentTarget.dataset.id;
      // 渠道列表接口
      getOrderChannelList(this.getChannelList).then(res => {
        let result = res.data.data;
        result.forEach(item => {
          this.channerllist = result;
          if (this.formInline.channel !== undefined) {
            if (item.channelKey == this.formInline.channel) {
              this.channerllist = result;
            } else {
              this.channerllist = result;
              this.formInline.channel = "";
            }
          }
        });
      });
    },
    // 排序
    changeTableSort(column) {
      // console.log('column',column.prop,column.order);
      if (column.prop === "orderTime" && column.order === "ascending") {
        this.formInline.orderTimeSort = 1;
        this.formInline.deliveryTimeSort = "";
        this.getList();
        // console.log('column',column.prop,column.order);
      } else if (column.prop === "orderTime" && column.order === "descending") {
        this.formInline.orderTimeSort = 2;
        this.formInline.deliveryTimeSort = "";
        this.getList();
        // console.log('column',column.prop,column.order);
      } else if (
        column.prop === "deliveryStartTime" &&
        column.order === "ascending"
      ) {
        this.formInline.deliveryTimeSort = 1;
        this.formInline.orderTimeSort = "";
        this.getList();
        // console.log('column',column.prop,column.order);
      } else if (
        column.prop === "deliveryStartTime" &&
        column.order === "descending"
      ) {
        this.formInline.deliveryTimeSort = 2;
        this.formInline.orderTimeSort = "";
        this.getList();
        // console.log('column',column.prop,column.order);
      }
    },
    // 操作按钮划进
    aditenterColor(index, row) {
      this.aditFlag = index;
    },
    // 操作按钮划出
    aditleaveColor(index, row) {
      this.aditFlag = null;
    },
    // 操作按钮划进
    dateenterColor(index, row) {
      this.dateFlag = index;
    },
    // 操作按钮划出
    dateleaveColor(index, row) {
      this.dateFlag = null;
    },
    // 操作按钮划进
    viewenterColor(index, row) {
      this.viewFlag = index;
    },
    // 操作按钮划出
    viewleaveColor(index, row) {
      this.viewFlag = null;
    },
    // 短信记录按钮划进
    SMSenterColor(index, row) {
      this.SMSFlag = index;
    },
    // 短信记录按钮划出
    SMSleaveColor(index, row) {
      this.SMSFlag = null;
    },
    // 短信发送按钮划进
    SMSsendenterColor(index, row) {
      this.SMSsendFlag = index;
    },
    // 短信发送按钮划出
    SMSsendleaveColor(index, row) {
      this.SMSsendFlag = null;
    },
    // 查看订单
    handleViewLog(index, row) {
      let newUrl = this.$router.resolve({
        path: "/viewOrdInfor",
        query: {
          id: row.id,
          cityId: row.deptId,
          deptName: row.deptName,
          kind: "Pending-orders"
          // paperName: this.paperName,
        }
      });
      let type = 101;
      let orderId = row.id;
      this.add0rderInquiry(orderId, type);
      window.open(newUrl.href, "_blank");
    },
    // 设置默认查询日期
    getDeliveryTime() {
      //前一天设定的日期时间
      let d = new Date();
      let year1, month1, day1;
      [year1, month1, day1] = [d.getFullYear(), d.getMonth(), d.getDate()];
      let date1 = new Date(year1, month1, day1, 0);
      let nowMonth1 =
        new Date().getMonth() + 1 < 10
          ? "0" + (new Date().getMonth() + 1)
          : new Date().getMonth() + 1;
      let nowDate1 =
        new Date().getDate() < 10
          ? "0" + new Date().getDate()
          : new Date().getDate();
      let deliveryStartTime =
        date1.getFullYear() +
        "-" +
        nowMonth1 +
        "-" +
        nowDate1 +
        " " +
        "00:00:00";
      this.timeValue.unshift();
      this.formInline.deliveryStartTime = deliveryStartTime;
      //当前设定的日期时间
      // let year2,month2,day2;
      // d.setTime(d.getTime()+7*24*60*60*1000+59*60);
      // [year2,month2,day2] = [d.getFullYear(),d.getMonth(),d.getDate()];
      // let date2 = new Date(year2, month2, day2,23,59,59);
      // let nowMonth2 = (date2.getMonth() + 1) < 10 ? "0" + (date2.getMonth() + 1) : (date2.getMonth() +
      //   1);
      // let nowDate2 = date2.getDate() < 10 ? "0" + date2.getDate() : date2.getDate();
      let date2 = new Date(year1, month1, day1, 23, 59, 59);
      let deliveryEndTime =
        date2.getFullYear() +
        "-" +
        nowMonth1 +
        "-" +
        nowDate1 +
        " " +
        "23:59:59";
      this.timeValue.push();
      this.formInline.deliveryEndTime = deliveryEndTime;
      // console.log('this.timeValue',this.timeValue,'deliveryStartTime',deliveryStartTime,deliveryEndTime)
    },
    // 转换成标准时间（开始）
    changeStartTime(deliveryTime) {
      let date1 = new Date(deliveryTime);
      let nowMonth1 =
        date1.getMonth() + 1 < 10
          ? "0" + (date1.getMonth() + 1)
          : date1.getMonth() + 1;
      let nowDate1 =
        date1.getDate() < 10 ? "0" + date1.getDate() : date1.getDate();
      return (deliveryTime =
        date1.getFullYear() +
        "-" +
        nowMonth1 +
        "-" +
        nowDate1 +
        " " +
        "00:00:00");
    },
    // 转换成标准时间（结束）
    changeEndTime(deliveryTime) {
      let date1 = new Date(deliveryTime);
      let nowMonth1 =
        date1.getMonth() + 1 < 10
          ? "0" + (date1.getMonth() + 1)
          : date1.getMonth() + 1;
      let nowDate1 =
        date1.getDate() < 10 ? "0" + date1.getDate() : date1.getDate();
      return (deliveryTime =
        date1.getFullYear() +
        "-" +
        nowMonth1 +
        "-" +
        nowDate1 +
        " " +
        "23:59:59");
    },
    // 查询配送时间
    queryTime() {
      if (this.formInline.select === "下单时间") {
        if (this.timeValue && this.timeValue.length) {
          this.formInline.orderTimeStart = this.timeValue[0] + ":00";
          this.formInline.orderTimeEnd = this.timeValue[1] + ":59";
        } else {
          this.formInline.orderTimeStart = "";
          this.formInline.orderTimeEnd = "";
        }
        // if(this.timeValue.length ==0) {
        //   this.formInline.orderTimeStart = '';
        //   this.formInline.orderTimeEnd ='';
        // } else {
        //   this.formInline.orderTimeStart = this.timeValue[0] + ':00';
        //   this.formInline.orderTimeEnd = this.timeValue[1] + ':59';
        // }
        this.isgreaterThan(
          this.formInline.orderTimeStart,
          this.formInline.orderTimeEnd
        );
        this.formInline.deliveryStartTime = "";
        this.formInline.deliveryEndTime = "";
      } else if (this.formInline.select === "配送时间") {
        if (this.timeValue && this.timeValue.length) {
          this.formInline.deliveryStartTime = this.timeValue[0] + ":00";
          this.formInline.deliveryEndTime = this.timeValue[1] + ":59";
        } else {
          this.formInline.deliveryStartTime = "";
          this.formInline.deliveryEndTime = "";
        }
        this.isgreaterThan(
          this.formInline.deliveryStartTime,
          this.formInline.deliveryEndTime
        );
        this.formInline.orderTimeStart = "";
        this.formInline.orderTimeEnd = "";
      } else {
        this.formInline.deliveryStartTime = "";
        this.formInline.deliveryEndTime = "";
        this.formInline.orderTimeStart = "";
        this.formInline.orderTimeEnd = "";
      }
    },
    // 判断是否大于31天
    isgreaterThan(time1, time2) {
      var data1 = Date.parse(time1.replace(/-/g, "/"));
      var data2 = Date.parse(time2.replace(/-/g, "/"));
      var datadiff = data2 - data1;
      var time = 31 * 24 * 60 * 60 * 1000;
      if (time1.length > 0 && time2.length > 0) {
        if (datadiff < 0 || datadiff > time) {
          this.$message.warning("时间间隔不可超过31天");
          return (this.timeValueFlag = true);
        } else {
          return (this.timeValueFlag = false);
        }
      }
    },
    // 查询短信记录
    handleSMS(index, row) {
      let newUrl = this.$router.resolve({
        path: "/SMSrecord",
        query: {
          id: row.id,
          cityId: row.deptId,
          deptName: row.deptName,
          kind: "SMS-orders"
          // paperName: this.paperName,
        }
      });
      window.open(newUrl.href, "_blank");
    },
    // 添加订单操作日志
    add0rderInquiry(orderId, type) {
      let queryOrder = {
        orderId,
        type,
        orderType: 1,
        workType: 0
      };
      add0rderOperateLog(queryOrder).then(res => {
        console.log("res", res.data.code);
      });
    },
    // 静止输入空格
    keydown(event) {
      if (event.keyCode == 32) {
        event.returnValue = false;
      }
      if (event.keyCode == 13) {
        this.$refs["channelTypeRef"].blur();
        this.$refs["channelRef"].blur();
        event.returnValue = false;
      }
    },
    // 回车事件
    keyupEnter() {
      // const that = this;
      if (window.event.keyCode == 13) {
        this.onSubmit();
      }
    },
    selectBlur(e) {
      if (e.keyCode == 13) {
        this.$refs["deptRef"].blur();
        this.$refs["statusRef"].blur();
        this.$refs["selectRef"].blur();
        this.$refs["barnchWarehouseRef"].blur();
        e.returnValue = false;
      }
    },
    handleSMSClose(action, done) {
      this.$refs.SMSruleForm.resetFields();
      this.SMSsendviewFlag = false;
    },
    // 打开短信发送弹窗
    handleSMSsend(index, row) {
      // console.log('row',row.receiverPhone.length,row,String(Number(row.receiverPhone)) === 'NaN');
      this.getSmsTemplatePageInfo();//
      this.orderId = row.id;
      this.getdefaulttem();
      this.SMSsendviewFlag = true;
    },
    // 获取默认模板
    getdefaulttem() {
      getDefaultSmsTemplate(
        {orderId: this.orderId}
      ).then(res => {
        if(String(Number(res.data.data.phoneNumbers)) !== 'NaN') this.SMSruleForm.phoneNumbers = Number(res.data.data.phoneNumbers);
        this.SMSruleForm.templateNames = res.data.data.templateName;
        this.SMSruleForm.content = res.data.data.content;
        this.SMSruleForm.templateName = res.data.data.templateName;
        this.SMSruleForm.orderId = res.data.data.orderId;
      })
    },
    // 短信发送
    SMSsubmitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.SMSruleForm.templateName = document.getElementById('InauirytempName').value;
          // console.log('this.SMSruleForm',this.SMSruleForm);
          sendInquirySms(this.SMSruleForm).then(res => {
            if(res.data.code == 200) {
              this.$message.success("发送成功");
              this.$refs[formName].resetFields();
              this.SMSsendviewFlag = false;
              // this.getList();
            }
          }).catch(error => {
            console.log(error)
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 短信发送取消
    SMSresetForm(formName) {
      this.$refs[formName].resetFields();
      this.SMSsendviewFlag = false;
    },
    getSmsTemplatePageInfo() {
      SmsTemplateNameAndContent({type:99}).then(res => {
        this.templateList = res.data.data;
      })
      this.SMSruleForm.content = this.SMSruleForm.templateNames;
    },
    temNselectBlur(e) {
      if(e.keyCode == 32) {
        e.returnValue = false;
      }
    }
  },
  destroyed() {
    window.removeEventListener("keydown",this.keyupEnter);
  },
  activated() {
    this.roleName = JSON.parse(window.localStorage.getItem('saber-userInfo')).content.authority;
    window.addEventListener("keydown", this.keyupEnter);
  },
  //如果页面有keep-alive缓存功能，这个函数会触发
  deactivated() {
    window.removeEventListener("keydown", this.keyupEnter);
  }
};
</script>

<style lang="scss">
.red {
  color: #ff0000;
}
.app-Inquiry {
  padding-right: 5px;
  .top-container {
    padding: 20px 10px 10px 20px;

    .el-form {
      .el-form-item {
        .line {
          margin: 0 3px;
          color: #8c919c;
        }
      }
    }

    .demo-form-inline {
      display: inline-block;
    }

    .el-form-item {
      margin-bottom: 20px !important;
    }
  }

  .table-container {
    padding-left: 20px;

    .table-top {
      font-size: 13px;
      th {
        padding: 5px 2px;
        .cell {
          padding: 0;
        }
      }
    }

    .el-table {
      .el-col-primary {
        margin: 0;
        padding: 2px 2px;
        font-size: 12px;
        font-weight: 400;
        border-radius: 4px;
        width: 78%;
        &.mainbutton {
          background: #ecf5ff;
          color: #409eff;
          border: 1px solid #b3d8ff;
        }

        &.dangerbutton {
          background: #fef0f0;
          color: #f56c6c;
          border: 1px solid #fbc4c4;
        }
        &.infobutton {
          background: #f4f4f5;
          color: #909399;
          border: 1px solid #d3d4d6;
        }
        &.warnbutton {
          background: #fdf6ec;
          color: #e6a23c;
          border: 1px solid #f5dab1;
        }
      }
    }

    .el-table__row {
      td {
        padding: 5px 2px;
        font-size: 13px;
        font-weight: 600;
        .cell {
          padding: 0;
          span {
            margin-left: 0;
          }
        }
      }
    }

    .active {
      color: #409eff;
      font-size: 13px;
      font-weight: 600;
    }

    .buttoncolor {
      color: #000;
      font-size: 13px;
      font-weight: 600;
    }

    .warning-row {
      background: oldlace;
      color: #e6a23c;
    }

    table {
      tr {
        td {
          border-right: 0 !important;
        }
      }
    }
  }
}
.el-date-range-picker .el-picker-panel__footer .el-button--text span {
  display: none;
}
.table-width {
  .el-table__fixed {
    .el-table__fixed-body-wrapper {
      .el-table__body {
        .el-table__row {
          td {
            .cell {
              span {
                margin-left: 0 !important;
              }
            }
          }
        }
      }
    }
  }
}
</style>
